package com.hsshy.beam.websocket;
import com.alibaba.fastjson.JSON;
import com.hsshy.beam.websocket.model.ChatMsg;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/websocket/{nickname}")
public class WebsocketServer {
    private static int COUNT = 0;


    private static Map<String, Session> map = new HashMap<String, Session>();

    /*
    建立连接的时候调用
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("nickname") String nickname) {


        map.put(nickname, session);

        addOnlineCount();
        System.out.println("当前在线人数：" + COUNT);
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setFromUser("");
        chatMsg.setToUser(chatMsg.getFromUser());
        chatMsg.setMsg("连接成功");
        chatMsg.setType(2);
        String result = JSON.toJSONString(chatMsg);
        sendMessage(session,result);

    }


    /*
    接收到客户端的信息
     */
    @OnMessage
    public void onMessage(String message,Session session,@PathParam("nickname") String nickname) {
        System.out.println("server 收到的信息是：" + message);



        ChatMsg chatMsg = JSON.parseObject(message, ChatMsg.class);

        if (chatMsg.getType() == 1) {
            //单聊.需要找到发送者和接受者.
//            chatMsg.setFromUser(session.getId());//发送者.
            chatMsg.setFromUser(nickname);//发送者.
            Session fromSession = map.get(chatMsg.getFromUser());
            Session toSession = map.get(chatMsg.getToUser());
            //发送给接受者.
            if (toSession != null) {

                //发送给发送者.
                sendMessage(fromSession,JSON.toJSONString(chatMsg));
                sendMessage(toSession,JSON.toJSONString(chatMsg));
            } else {
                //发送给发送者.
                chatMsg.setFromUser("");
                chatMsg.setToUser(chatMsg.getFromUser());
                chatMsg.setMsg("系统消息：对方不在线或者您输入的频道号不对");
                chatMsg.setType(2);
                String result = JSON.toJSONString(chatMsg);
                sendMessage(fromSession,result);
            }
        } else if(chatMsg.getType()==0) {
            //群发消息
            broadcast(JSON.toJSONString(chatMsg));
        }


    }

    public void broadcast(String message) {

        for (Session session : map.values()) {
            session.getAsyncRemote().sendText(message);
        }
    }

    public void sendMessage(Session session,String message)  {
        try {
            session.getBasicRemote().sendText(message);
            //this.session.getAsyncRemote().sendText(message);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

    @OnClose
    public void onclose(@PathParam("nickname") String nickname) {
        map.remove(nickname);
        subOnlineCount();
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }







    public static synchronized int getOnlineCount() {
        return COUNT;
    }

    public static synchronized void addOnlineCount() {
        WebsocketServer.COUNT++;
    }

    public static synchronized void subOnlineCount() {
        WebsocketServer.COUNT--;
    }
}